package dao

import (
	"fmt"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/models/refunds"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
)

type RefundDao struct {
}

func NewRefundDao() *RefundDao {
	return &RefundDao{}
}

func (d *RefundDao) CountRefundByRefundNo(refundNo string) *dingo.ErrorWrap {
	var count int64
	sql := "select count(*) from refunds where refund_no = ? "
	db := global.Orm.Raw(sql, refundNo).Count(&count)
	return dingo.ErrorIf(db.Error, count)
}

func (d *RefundDao) CountRefundByOutRefundNo(outRefundNo string) *dingo.ErrorWrap {
	var count int64
	sql := "select count(1) from refunds where out_refund_no = ? "
	db := global.Orm.Raw(sql, outRefundNo).Count(&count)
	return dingo.ErrorIf(db.Error, count)
}

func (d *RefundDao) CountRefundByTradeNo(tradeNo string) *dingo.ErrorWrap {
	var count int64
	sql := "select count(1) from refunds where trade_no = ? "
	db := global.Orm.Raw(sql, tradeNo).Count(&count)
	return dingo.ErrorIf(db.Error, count)
}

func (d *RefundDao) InsertRefund(m *refunds.RefundModel) *dingo.ErrorWrap {
	db := global.Orm.Debug().Table("refunds").Create(m)
	return dingo.ErrorIf(db.Error, true)
}

func (d *RefundDao) DeleteRefundNull(tradeNo string) *dingo.ErrorWrap {
	db := global.Orm.Debug().Exec("delete from refunds where refund_no = '' and out_refund_no = '' and  trade_no = ?", tradeNo)
	return dingo.ErrorIf(db.Error, true)
}

func (d *RefundDao) GetRefundListInfo(param *request.RefundListReq) *dingo.ErrorWrap {
	var (
		lst    []*refunds.RefundModel
		count  int64
		limit  int = param.PageSize
		offset int = param.PageSize * (param.PageNo - 1)
	)
	db := global.Orm.Table("refunds")

	if param.TradeNo != "" {
		db.Where("trade_no like ?", fmt.Sprint("%", param.TradeNo, "%"))
	}

	if param.OutTradeNo != "" {
		db.Where("out_trade_no like ?", fmt.Sprint("%", param.OutTradeNo, "%"))
	}

	db.Order("success_time desc")

	db.Limit(limit).Offset(offset).Find(&lst).Limit(-1).Offset(-1).Count(&count)

	return dingo.ErrorIf(db.Error, lst, count)
}
